<script lang="ts" setup>
import {ref, onMounted, onBeforeUnmount, shallowRef, watch} from 'vue'
import {Upload, Edit, Delete, Picture, Star, StarFilled} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus"
import {getPageScripts, saveScript, putScript, deleteScript, getTagsByName, uploadFile, getCategoriesByName} from '@/api/admin'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const editEditorRef = shallowRef()

// 工具栏配置
const toolbarConfig = {
  excludeKeys: [
    'uploadVideo',
    'insertTable',
    'codeBlock',
    'fullScreen'
  ]
}

// 编辑器配置
const editorConfig = { 
  placeholder: '请输入剧本简介...',
  MENU_CONF: {
    uploadImage: {
      server: '/api/upload', // 这里会被自定义上传函数覆盖
      fieldName: 'file',
      maxFileSize: 5 * 1024 * 1024, // 5MB
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      customInsert(res, insertFn) {
        // 自定义插入图片
        if (res.data && res.data.url) {
          insertFn(res.data.url, res.data.alt || '', res.data.href || '')
        }
      },
      customUpload(file, insertFn) {
        // 自定义上传
        handleImageUpload(file, insertFn)
      },
      onError(file, err, res) {
        ElMessage.error('图片上传失败')
        console.error('图片上传错误:', err)
      },
      onProgress(file, progress) {
        console.log('上传进度:', progress)
      }
    }
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleDateString('zh-CN')
}

// 表格数据
const tableData = ref([])

// 分页参数
const getPageScriptsData = ref({
  name: "",
  supportCount: "",
  tagName: "",
  categoryName: "",
  pageNo: "1",
  pageSize: "10",
})

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const detailDialogVisible = ref(false)

// 表单数据
const form = ref({
  id: null, // 新增时ID为null
  name: "",
  author: "",
  coverImage: "",
  pricePerUser: "",
  duration: "",
  level: "",
  description: "",
  isTop: false, // 改为布尔值
  isNew: false, // 改为布尔值
  isLimited: 1,
  category: "",
  supportCount: [],
  tagName: []
})

const supportCountInputValue = ref('')

// 编辑表单数据
const editForm = ref({
  id: null, // 编辑时ID为实际值
  name: "",
  author: "",
  coverImage: "",
  pricePerUser: "",
  duration: "",
  level: "",
  description: "",
  isTop: false, // 改为布尔值以支持复选框
  isNew: false, // 改为布尔值以支持复选框
  isLimited: 1,
  category: "",
  supportCount: [],
  tagName: []
})

const editSupportCountInputValue = ref('')

// 删除相关
const deleteScriptId = ref(null)
const deleteScriptName = ref(null)

// 标签自动补全相关
const tagInputValue = ref('')
const editTagInputValue = ref('')

// 详情数据
const detailData = ref({
  id: null, // 详情时ID为实际值
  name: "",
  author: "",
  coverImage: "",
  pricePerUser: "",
  duration: "",
  level: "",
  description: "",
  isTop: 0,
  isNew: 0,
  isLimited: 1,
  category: "",
  supportCount: [],
  tagName: []
})

// 编辑器创建处理
const handleCreated = (editor) => {
  editorRef.value = editor
}

const handleEditCreated = (editor) => {
  editEditorRef.value = editor
}

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor != null) {
    editor.destroy()
  }
  
  const editEditor = editEditorRef.value
  if (editEditor != null) {
    editEditor.destroy()
  }
})

// 获取剧本列表
const getScripts = async () => {
  try {
    const response = await getPageScripts(getPageScriptsData.value)
    console.log('API Response:', response)
    if (response.data && response.data.results) {
      tableData.value = response.data.results
      total.value = response.data.total
    } else {
      ElMessage.error('返回的数据结构不正确')
    }
  } catch (error) {
    ElMessage.error('获取剧本列表失败')
    console.error(error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  getScripts()
})

// 分页处理
const handleSizeChange = (val) => {
  getPageScriptsData.value.pageSize = val.toString()
  getPageScriptsData.value.pageNo = "1"
  currentPage.value = 1
  getScripts()
}

const handleCurrentChange = (val) => {
  getPageScriptsData.value.pageNo = val.toString()
  currentPage.value = val
  getScripts()
}

// 搜索
const onSubmit = () => {
  getPageScriptsData.value.pageNo = "1"
  currentPage.value = 1
  getScripts()
}

// 重置搜索
const onSubmitEmpty = () => {
  getPageScriptsData.value.name = ""
  getPageScriptsData.value.supportCount = ""
  getPageScriptsData.value.tagName = ""
  getPageScriptsData.value.categoryName = ""
  getPageScriptsData.value.pageNo = "1"
  currentPage.value = 1
  getScripts()
}

// 清空表单
const clearForm = () => {
  form.value = {
    id: null, // 新增时ID为null
    name: "",
    author: "",
    coverImage: "",
    pricePerUser: "",
    duration: "",
    level: "",
    description: "",
    isTop: false, // 改为布尔值
    isNew: false, // 改为布尔值
    isLimited: 1,
    category: "",
    supportCount: [],
    tagName: []
  }
  supportCountInputValue.value = ''
  // 清空富文本编辑器内容
  if (editorRef.value) {
    editorRef.value.setHtml('')
  }
}

// 新增剧本
const addScript = () => {
  clearForm()
  addDialogVisible.value = true
}

// 新增表单支持人数同步
watch(
  () => form.value.supportCount,
  (val) => {
    supportCountInputValue.value = Array.isArray(val) ? val.join(', ') : (val || '')
  },
  { immediate: true }
)

const saveScriptData = async () => {
  try {
    // 数据验证
    if (!form.value.name || !form.value.name.trim()) {
      ElMessage.error('请输入剧本名称')
      return
    }
    if (!form.value.author || !form.value.author.trim()) {
      ElMessage.error('请输入作者')
      return
    }
    if (!form.value.pricePerUser || Number(form.value.pricePerUser) <= 0) {
      ElMessage.error('请输入有效的价格')
      return
    }
    if (!form.value.duration || !form.value.duration.trim()) {
      ElMessage.error('请输入剧本时长')
      return
    }
    if (!form.value.level) {
      ElMessage.error('请选择难度等级')
      return
    }
    if (!form.value.category || !form.value.category.trim()) {
      ElMessage.error('请输入分类')
      return
    }
    // 支持人数字符串转数组
    form.value.supportCount = supportCountInputValue.value
      .split(',')
      .map(item => parseInt(item.trim()))
      .filter(item => !isNaN(item))
    // 确保数据格式正确
    const submitData = {
      id: form.value.id || null, // 新增时传null，修改时传实际ID
      name: form.value.name.trim(),
      author: form.value.author.trim(),
      coverImage: form.value.coverImage,
      pricePerUser: form.value.pricePerUser,
      duration: form.value.duration.trim(),
      level: form.value.level,
      description: form.value.description,
      isTop: form.value.isTop ? 1 : 0,
      isNew: form.value.isNew ? 1 : 0,
      isLimited: form.value.isLimited || 1,
      category: form.value.category.trim(),
      supportCount: Array.isArray(form.value.supportCount) ? form.value.supportCount : [],
      tagName: Array.isArray(form.value.tagName) ? form.value.tagName : []
    }
    await saveScript(submitData)
    ElMessage.success("保存剧本成功")
    addDialogVisible.value = false
    getScripts()
  } catch (error) {
    ElMessage.error("保存剧本失败")
    console.error(error)
  }
}

// 编辑剧本
const editScript = (row) => {
  editForm.value = {
    ...row,
    // 将数字状态转换为布尔值
    isTop: row.isTop === 1,
    isNew: row.isNew === 1
  }
  // 同步支持人数输入框
  editSupportCountInputValue.value = Array.isArray(row.supportCount) ? row.supportCount.join(', ') : (row.supportCount || '')
  editDialogVisible.value = true
  
  // 等待编辑器创建完成后设置内容
  setTimeout(() => {
    if (editEditorRef.value) {
      editEditorRef.value.setHtml(editForm.value.description || '')
    }
  }, 100)
}

// 编辑表单支持人数同步
watch(
  () => editForm.value.supportCount,
  (val) => {
    editSupportCountInputValue.value = Array.isArray(val) ? val.join(', ') : (val || '')
  },
  { immediate: true }
)

const updateScript = async () => {
  try {
    // 数据验证
    if (!editForm.value.name || !editForm.value.name.trim()) {
      ElMessage.error('请输入剧本名称')
      return
    }
    if (!editForm.value.author || !editForm.value.author.trim()) {
      ElMessage.error('请输入作者')
      return
    }
    if (!editForm.value.pricePerUser || Number(editForm.value.pricePerUser) <= 0) {
      ElMessage.error('请输入有效的价格')
      return
    }
    if (!editForm.value.duration || !editForm.value.duration.trim()) {
      ElMessage.error('请输入剧本时长')
      return
    }
    if (!editForm.value.level) {
      ElMessage.error('请选择难度等级')
      return
    }
    if (!editForm.value.category || !editForm.value.category.trim()) {
      ElMessage.error('请输入分类')
      return
    }
    // 支持人数字符串转数组
    editForm.value.supportCount = editSupportCountInputValue.value
      .split(',')
      .map(item => parseInt(item.trim()))
      .filter(item => !isNaN(item))
    // 将布尔值转换回数字格式，确保数据格式正确
    const submitData = {
      id: editForm.value.id,
      name: editForm.value.name.trim(),
      author: editForm.value.author.trim(),
      coverImage: editForm.value.coverImage,
      pricePerUser: editForm.value.pricePerUser,
      duration: editForm.value.duration.trim(),
      level: editForm.value.level,
      description: editForm.value.description,
      isTop: editForm.value.isTop ? 1 : 0,
      isNew: editForm.value.isNew ? 1 : 0,
      isLimited: editForm.value.isLimited || 1,
      category: editForm.value.category.trim(),
      supportCount: Array.isArray(editForm.value.supportCount) ? editForm.value.supportCount : [],
      tagName: Array.isArray(editForm.value.tagName) ? editForm.value.tagName : []
    }
    await putScript(submitData)
    ElMessage.success("保存剧本成功")
    editDialogVisible.value = false
    getScripts()
  } catch (error) {
    ElMessage.error("保存剧本失败")
    console.error(error)
  }
}

// 删除剧本
const removeScript = (row) => {
  deleteScriptId.value = row.id
  deleteScriptName.value = row.name
  deleteDialogVisible.value = true
}

const confirmDelete = async () => {
  try {
    await deleteScript(deleteScriptId.value)
    ElMessage.success("删除剧本成功")
    deleteDialogVisible.value = false
    getScripts()
  } catch (error) {
    ElMessage.error("删除剧本失败")
    console.error(error)
  }
}

// 获取标签建议
const getTagSuggestions = async (queryString, callback) => {
  try {
    const response = await getTagsByName(queryString || '')
    if (response.data && Array.isArray(response.data)) {
      const suggestions = response.data.map(tag => ({ value: tag }))
      callback(suggestions)
    } else {
      callback([])
    }
  } catch (error) {
    console.error('获取标签建议失败:', error)
    callback([])
  }
}

// 获取分类建议
const getCategorySuggestions = async (queryString, callback) => {
  try {
    const response = await getCategoriesByName(queryString || '')
    if (response.data && Array.isArray(response.data)) {
      const suggestions = response.data.map(category => ({ value: category }))
      callback(suggestions)
    } else {
      callback([])
    }
  } catch (error) {
    console.error('获取分类建议失败:', error)
    callback([])
  }
}

// 标签选择处理
const handleTagSelect = (item) => {
  if (item && item.value && !form.value.tagName.includes(item.value)) {
    form.value.tagName.push(item.value)
  }
  tagInputValue.value = ''
}

// 编辑标签选择处理
const handleEditTagSelect = (item) => {
  if (item && item.value && !editForm.value.tagName.includes(item.value)) {
    editForm.value.tagName.push(item.value)
  }
  editTagInputValue.value = ''
}

// 移除标签
const removeTag = (index) => {
  form.value.tagName.splice(index, 1)
}

// 移除编辑标签
const removeEditTag = (index) => {
  editForm.value.tagName.splice(index, 1)
}

// 标签输入处理
const handleTagEnter = () => {
  if (tagInputValue.value && !form.value.tagName.includes(tagInputValue.value)) {
    form.value.tagName.push(tagInputValue.value)
    tagInputValue.value = ''
  }
}

// 编辑标签输入处理
const handleEditTagEnter = () => {
  if (editTagInputValue.value && !editForm.value.tagName.includes(editTagInputValue.value)) {
    editForm.value.tagName.push(editTagInputValue.value)
    editTagInputValue.value = ''
  }
}

// 文件上传相关
const uploadLoading = ref(false)
const editUploadLoading = ref(false)

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 新增剧本图片上传
const handleCoverUpload = async (file) => {
  if (!beforeUpload(file)) {
    return false
  }
  
  try {
    uploadLoading.value = true
    const response = await uploadFile(file)
    if (response.data && response.data.url) {
      form.value.coverImage = response.data.url
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error('图片上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
    console.error(error)
  } finally {
    uploadLoading.value = false
  }
  return false // 阻止默认上传行为
}

// 编辑剧本图片上传
const handleEditCoverUpload = async (file) => {
  if (!beforeUpload(file)) {
    return false
  }
  
  try {
    editUploadLoading.value = true
    const response = await uploadFile(file)
    if (response.data && response.data.url) {
      editForm.value.coverImage = response.data.url
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error('图片上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
    console.error(error)
  } finally {
    editUploadLoading.value = false
  }
  return false // 阻止默认上传行为
}

// 查看剧本详情
const viewScriptDetail = (row) => {
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

// 从详情页面编辑剧本
const editFromDetail = () => {
  // 关闭详情弹窗
  detailDialogVisible.value = false
  
  // 设置编辑表单数据，将数字状态转换为布尔值
  editForm.value = {
    ...detailData.value,
    isTop: detailData.value.isTop === 1,
    isNew: detailData.value.isNew === 1
  }
  
  // 打开编辑弹窗
  editDialogVisible.value = true
  
  // 等待编辑器创建完成后设置内容
  setTimeout(() => {
    if (editEditorRef.value) {
      editEditorRef.value.setHtml(editForm.value.description || '')
    }
  }, 100)
}

// 图片上传处理函数
const handleImageUpload = async (file, insertFn) => {
  try {
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('只能上传图片文件!')
      return
    }
    
    // 验证文件大小
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过 5MB!')
      return
    }
    
    // 调用上传接口
    const response = await uploadFile(file)
    
    if (response.data && response.data.url) {
      // 插入图片到编辑器
      insertFn(response.data.url, file.name, '')
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error('图片上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
    console.error('图片上传错误:', error)
  }
}
</script>

<template>
  <!-- 剧本列表 -->
  <el-card>
    <div class="card-header">
      <span>剧本管理</span>
      <div class="header-buttons">
        <el-button @click="$router.push('/admin')" style="margin-right: 10px;">
          返回管理后台
        </el-button>
        <el-button type="primary" @click="addScript">
          新增剧本
          <el-icon class="el-icon--right">
            <Upload/>
          </el-icon>
        </el-button>
      </div>
    </div>
    <el-divider/>

    <!-- 搜索表单 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input
            v-model="getPageScriptsData.name"
            style="width: 200px"
            placeholder="请输入剧本名称"
        />
      </el-form-item>
      <el-form-item>
        <el-input
            v-model="getPageScriptsData.supportCount"
            style="width: 150px"
            placeholder="支持人数"
        />
      </el-form-item>
      <el-form-item>
        <el-input
            v-model="getPageScriptsData.tagName"
            style="width: 150px"
            placeholder="标签名称"
        />
      </el-form-item>
      <el-form-item>
        <el-input
            v-model="getPageScriptsData.categoryName"
            style="width: 150px"
            placeholder="分类名称"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="onSubmitEmpty">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 剧本表格 -->
    <el-table 
      :data="tableData" 
      style="width: 100%"
      @row-click="viewScriptDetail"
      :row-class-name="'clickable-row'"
    >
      <el-table-column prop="name" label="剧本名称" width="200" show-overflow-tooltip/>
      <el-table-column prop="author" label="作者" width="100"/>
      <el-table-column prop="coverImage" label="封面" width="70">
        <template #default="{ row }">
          <el-image
              v-if="row.coverImage"
              :src="row.coverImage"
              style="width: 45px; height: 60px"
              fit="cover"
          />
          <span v-else style="color: #909399; font-size: 11px;">无封面</span>
        </template>
      </el-table-column>
      <el-table-column prop="pricePerUser" label="价格" width="90" align="center">
        <template #default="{ row }">
          <span style="color: #e6a23c; font-weight: bold;">¥{{ row.pricePerUser }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="duration" label="时长" width="90" align="center"/>
      <el-table-column prop="level" label="难度" width="90" align="center">
        <template #default="{ row }">
          <el-tag 
            :type="row.level === '新手' ? 'success' : row.level === '进阶' ? 'warning' : 'danger'"
            size="small"
          >
            {{ row.level }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="分类" width="100"/>
      <el-table-column prop="supportCount" label="支持人数" width="110" align="center">
        <template #default="{ row }">
          <span style="color: #409eff;">
            {{ Array.isArray(row.supportCount) ? row.supportCount.join(', ') : row.supportCount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="tagName" label="标签" min-width="180">
        <template #default="{ row }">
          <div class="tag-list">
            <el-tag 
              v-for="(tag, index) in (Array.isArray(row.tagName) ? row.tagName : [])" 
              :key="index"
              type="primary"
              effect="plain"
              size="small"
              style="margin: 1px 3px 1px 0;"
            >
              {{ tag }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <div class="status-list">
            <el-tag v-if="row.isTop" type="success" size="small" style="margin: 1px;">置顶</el-tag>
            <el-tag v-if="row.isNew" type="warning" size="small" style="margin: 1px;">新品</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140" fixed="right" align="center">
        <template #default="{ row }">
          <div @click.stop>
            <el-button type="primary" plain size="small" @click="editScript(row)">
              <el-icon>
                <Edit/>
              </el-icon>
              编辑
            </el-button>
            <el-button type="danger" plain size="small" @click="removeScript(row)">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination
          class="el-p"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 15, 20, 25]"
          layout="jumper, total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 新增剧本弹窗 -->
  <el-dialog
      v-model="addDialogVisible"
      title="新增剧本"
      width="1000px"
  >
    <el-form :model="form" label-width="120px">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="剧本名称" required>
            <el-input v-model="form.name" placeholder="请输入剧本名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="作者" required>
            <el-input v-model="form.author" placeholder="请输入作者"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="价格" required>
            <el-input-number v-model="form.pricePerUser" :min="0" placeholder="请输入价格" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="时长" required>
            <el-input v-model="form.duration" placeholder="请输入时长"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="难度" required>
            <el-select v-model="form.level" placeholder="请选择难度" style="width: 100%;">
              <el-option label="新手" value="新手"/>
              <el-option label="进阶" value="进阶"/>
              <el-option label="硬核" value="硬核"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类" required>
            <el-autocomplete
              v-model="form.category"
              :fetch-suggestions="getCategorySuggestions"
              placeholder="请输入分类"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="封面图片">
            <el-upload
              class="cover-uploader"
              :show-file-list="false"
              :before-upload="handleCoverUpload"
              :loading="uploadLoading"
              accept="image/*"
            >
              <div v-if="form.coverImage" class="cover-preview">
                <el-image
                  :src="form.coverImage"
                  fit="cover"
                  style="width: 120px; height: 160px; border-radius: 4px;"
                />
                <div class="cover-overlay">
                  <el-icon><Upload /></el-icon>
                  <span>点击更换</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon><Upload /></el-icon>
                <div class="upload-text">点击上传封面图片</div>
                <div class="upload-tip">支持 JPG、PNG 格式，大小不超过 5MB</div>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支持人数">
            <el-input
              v-model="supportCountInputValue"
              placeholder="请输入支持人数，多个用逗号分隔，如：6,7,8"
            />
          </el-form-item>
          <el-form-item label="标签">
            <el-autocomplete
              v-model="tagInputValue"
              :fetch-suggestions="getTagSuggestions"
              placeholder="请输入标签"
              clearable
              @select="handleTagSelect"
              @keyup.enter="handleTagEnter"
              style="width: 100%"
            />
            <div class="tag-display" v-if="form.tagName.length > 0">
              <el-tag
                v-for="(tag, index) in form.tagName"
                :key="index"
                closable
                @close="removeTag(index)"
                type="primary"
                effect="plain"
                style="margin: 4px 4px 4px 0;"
              >
                {{ tag }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item label="状态">
            <el-checkbox v-model="form.isTop">置顶</el-checkbox>
            <el-checkbox v-model="form.isNew">新品</el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="剧本简介">
        <div style="border: 1px solid #ccc; border-radius: 4px;">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            mode="default"
          />
          <Editor
            style="height: 300px; overflow-y: hidden;"
            v-model="form.description"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveScriptData">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑剧本弹窗 -->
  <el-dialog
      v-model="editDialogVisible"
      title="编辑剧本"
      width="1000px"
  >
    <el-form :model="editForm" label-width="120px">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="剧本名称" required>
            <el-input v-model="editForm.name" placeholder="请输入剧本名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="作者" required>
            <el-input v-model="editForm.author" placeholder="请输入作者"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="价格" required>
            <el-input-number v-model="editForm.pricePerUser" :min="0" placeholder="请输入价格" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="时长" required>
            <el-input v-model="editForm.duration" placeholder="请输入时长"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="难度" required>
            <el-select v-model="editForm.level" placeholder="请选择难度" style="width: 100%;">
              <el-option label="新手" value="新手"/>
              <el-option label="进阶" value="进阶"/>
              <el-option label="硬核" value="硬核"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类" required>
            <el-autocomplete
              v-model="editForm.category"
              :fetch-suggestions="getCategorySuggestions"
              placeholder="请输入分类"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="封面图片">
            <el-upload
              class="cover-uploader"
              :show-file-list="false"
              :before-upload="handleEditCoverUpload"
              :loading="editUploadLoading"
              accept="image/*"
            >
              <div v-if="editForm.coverImage" class="cover-preview">
                <el-image
                  :src="editForm.coverImage"
                  fit="cover"
                  style="width: 120px; height: 160px; border-radius: 4px;"
                />
                <div class="cover-overlay">
                  <el-icon><Upload /></el-icon>
                  <span>点击更换</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon><Upload /></el-icon>
                <div class="upload-text">点击上传封面图片</div>
                <div class="upload-tip">支持 JPG、PNG 格式，大小不超过 5MB</div>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支持人数">
            <el-input
              v-model="editSupportCountInputValue"
              placeholder="请输入支持人数，多个用逗号分隔，如：6,7,8"
            />
          </el-form-item>
          <el-form-item label="标签">
            <el-autocomplete
              v-model="editTagInputValue"
              :fetch-suggestions="getTagSuggestions"
              placeholder="请输入标签"
              clearable
              @select="handleEditTagSelect"
              @keyup.enter="handleEditTagEnter"
              style="width: 100%"
            />
            <div class="tag-display" v-if="editForm.tagName.length > 0">
              <el-tag
                v-for="(tag, index) in editForm.tagName"
                :key="index"
                closable
                @close="removeEditTag(index)"
                type="primary"
                effect="plain"
                style="margin: 4px 4px 4px 0;"
              >
                {{ tag }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item label="状态">
            <el-checkbox v-model="editForm.isTop">置顶</el-checkbox>
            <el-checkbox v-model="editForm.isNew">新品</el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="剧本简介">
        <div style="border: 1px solid #ccc; border-radius: 4px;">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editEditorRef"
            :defaultConfig="toolbarConfig"
            mode="default"
          />
          <Editor
            style="height: 300px; overflow-y: hidden;"
            v-model="editForm.description"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleEditCreated"
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateScript">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 删除确认弹窗 -->
  <el-dialog
      v-model="deleteDialogVisible"
      :title="`您确认要删除剧本「${deleteScriptName}」吗？`"
      width="500px"
  >
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 剧本详情弹窗 -->
  <el-dialog
      v-model="detailDialogVisible"
      title="剧本详情"
      width="800px"
  >
    <div class="script-detail">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="cover-section">
            <el-image
              v-if="detailData.coverImage"
              :src="detailData.coverImage"
              style="width: 100%; height: 300px; border-radius: 8px;"
              fit="cover"
            />
            <div v-else class="no-cover">
              <el-icon style="font-size: 48px; color: #c0c4cc;"><Picture /></el-icon>
              <div style="margin-top: 8px; color: #909399;">暂无封面</div>
            </div>
            
            <!-- 标签和状态区域 -->
            <div class="cover-bottom-info">
              <div class="tags-status-row">
                <div class="tags-group">
                  <span class="info-label">标签：</span>
                  <div class="detail-tag-list">
                    <el-tag 
                      v-for="(tag, index) in (Array.isArray(detailData.tagName) ? detailData.tagName : [])" 
                      :key="index"
                      type="primary"
                      effect="light"
                      size="small"
                      style="margin: 0 4px 4px 0; padding: 4px 8px; border-radius: 12px;"
                    >
                      {{ tag }}
                    </el-tag>
                    <span v-if="!detailData.tagName || detailData.tagName.length === 0" class="no-data">暂无标签</span>
                  </div>
                </div>
                
                <div class="status-group">
                  <span class="info-label">状态：</span>
                  <div class="detail-status-list">
                    <el-tag v-if="detailData.isTop" type="success" size="small" style="margin: 0 4px 4px 0; padding: 4px 8px; border-radius: 12px;">
                      <el-icon style="margin-right: 2px; font-size: 12px;"><Star /></el-icon>
                      置顶
                    </el-tag>
                    <el-tag v-if="detailData.isNew" type="warning" size="small" style="margin: 0 4px 4px 0; padding: 4px 8px; border-radius: 12px;">
                      <el-icon style="margin-right: 2px; font-size: 12px;"><StarFilled /></el-icon>
                      新品
                    </el-tag>
                    <span v-if="!detailData.isTop && !detailData.isNew" class="no-data">无特殊状态</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="info-section">
            <h2 class="script-title">{{ detailData.name }}</h2>
            <div class="script-meta">
              <div class="meta-item">
                <span class="label">作者：</span>
                <span class="value">{{ detailData.author }}</span>
              </div>
              <div class="meta-item">
                <span class="label">价格：</span>
                <span class="value price">¥{{ detailData.pricePerUser }}</span>
              </div>
              <div class="meta-item">
                <span class="label">时长：</span>
                <span class="value">{{ detailData.duration }}</span>
              </div>
              <div class="meta-item">
                <span class="label">难度：</span>
                <el-tag 
                  :type="detailData.level === '新手' ? 'success' : detailData.level === '进阶' ? 'warning' : 'danger'"
                  size="small"
                >
                  {{ detailData.level }}
                </el-tag>
              </div>
              <div class="meta-item">
                <span class="label">分类：</span>
                <span class="value">{{ detailData.category }}</span>
              </div>
              <div class="meta-item">
                <span class="label">支持人数：</span>
                <span class="value">{{ Array.isArray(detailData.supportCount) ? detailData.supportCount.join(', ') : detailData.supportCount }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <div class="description-section">
        <div class="section-title">剧本简介</div>
        <div class="description-content" v-html="detailData.description || '暂无简介'"></div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="editFromDetail">编辑剧本</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-p {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.demo-form-inline {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 1px;
}

.status-list {
  display: flex;
  flex-wrap: wrap;
  gap: 1px;
  justify-content: center;
}

.tag-display {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.cover-uploader {
  width: 120px;
  height: 160px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  position: relative;
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  opacity: 0;
  transition: opacity 0.3s;
}

.cover-preview:hover .cover-overlay {
  opacity: 1;
}

.cover-overlay .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #909399;
}

.upload-placeholder .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.upload-text {
  color: #909399;
  font-size: 14px;
  margin-top: 8px;
}

.upload-tip {
  color: #c0c4cc;
  font-size: 12px;
  margin-top: 4px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
  font-size: 13px;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
  padding: 10px 0;
  font-size: 13px;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table .cell) {
  padding: 0 8px;
}

/* 按钮组样式优化 */
:deep(.el-button + .el-button) {
  margin-left: 4px;
}

/* 可点击行样式 */
.clickable-row {
  cursor: pointer;
  transition: background-color 0.2s;
}

.clickable-row:hover {
  background-color: #f5f7fa !important;
}

/* 剧本详情样式 */
.script-detail {
  padding: 20px 0;
}

.cover-section {
  text-align: center;
}

.no-cover {
  width: 100%;
  height: 300px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.script-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.script-meta {
  margin-bottom: 24px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.meta-item .label {
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.meta-item .value {
  color: #303133;
}

.meta-item .price {
  color: #e6a23c;
  font-weight: bold;
  font-size: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.tags-section,
.status-section {
  margin-bottom: 24px;
}

.description-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

.tags-section {
  margin-bottom: 24px;
}

.detail-tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.status-section {
  margin-bottom: 24px;
}

.detail-status-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.no-data {
  color: #909399;
  font-size: 14px;
  font-style: italic;
}

/* 标签和状态标签的悬停效果 */
.detail-tag-list .el-tag:hover,
.detail-status-list .el-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.cover-bottom-info {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.tags-status-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
}

.tags-group,
.status-group {
  flex: 1;
  display: flex;
  align-items: flex-start;
}

.info-label {
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  white-space: nowrap;
  margin-top: 2px;
}

.detail-tag-list,
.detail-status-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  flex: 1;
}

.no-data {
  color: #909399;
  font-size: 12px;
  font-style: italic;
}

/* 弹窗样式优化 */
:deep(.el-dialog) {
  overflow: visible !important;
}

:deep(.el-dialog__body) {
  overflow: visible !important;
}

:deep(.el-form) {
  overflow: visible !important;
}

/* 富文本编辑器样式优化 */
:deep(.w-e-text-container) {
  background-color: #fff !important;
}

:deep(.w-e-toolbar) {
  background-color: #f8f9fa !important;
  border-bottom: 1px solid #e9ecef !important;
}

:deep(.w-e-bar-item button) {
  color: #495057 !important;
}

:deep(.w-e-bar-item button:hover) {
  background-color: #e9ecef !important;
}

:deep(.w-e-text-container [data-slate-editor]) {
  padding: 12px !important;
  line-height: 1.6 !important;
}

/* 图片上传相关样式 */
:deep(.w-e-text-container img) {
  max-width: 100% !important;
  height: auto !important;
  border-radius: 4px !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
  margin: 8px 0 !important;
}

:deep(.w-e-text-container img:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  transition: box-shadow 0.2s ease !important;
}

/* 上传进度条样式 */
:deep(.w-e-upload-progress) {
  background-color: #f0f9ff !important;
  border: 1px solid #409eff !important;
  border-radius: 4px !important;
  padding: 8px !important;
  margin: 8px 0 !important;
}

:deep(.w-e-upload-progress-bar) {
  background-color: #409eff !important;
  height: 4px !important;
  border-radius: 2px !important;
  transition: width 0.3s ease !important;
}

/* 详情页面富文本内容样式 */
.description-content {
  line-height: 1.6;
  color: #606266;
  max-height: 300px;
  overflow-y: auto;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 6px;
}

.description-content :deep(p) {
  margin: 0 0 12px 0;
}

.description-content :deep(p:last-child) {
  margin-bottom: 0;
}

.description-content :deep(strong) {
  font-weight: bold;
  color: #303133;
}

.description-content :deep(em) {
  font-style: italic;
}

.description-content :deep(h1),
.description-content :deep(h2),
.description-content :deep(h3),
.description-content :deep(h4),
.description-content :deep(h5),
.description-content :deep(h6) {
  margin: 16px 0 8px 0;
  color: #303133;
  font-weight: 600;
}

.description-content :deep(ul),
.description-content :deep(ol) {
  margin: 8px 0;
  padding-left: 20px;
}

.description-content :deep(li) {
  margin: 4px 0;
}

.description-content :deep(blockquote) {
  margin: 12px 0;
  padding: 8px 12px;
  border-left: 4px solid #409eff;
  background-color: #f0f9ff;
  color: #606266;
}

.description-content :deep(code) {
  background-color: #f1f3f4;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.description-content :deep(pre) {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 12px 0;
}

.description-content :deep(pre code) {
  background-color: transparent;
  padding: 0;
}
</style> 